//
//  InputViewController.m
//  RomensBI
//
//  Created by 裴飞杨 on 2017/7/14.
//
//

#import "InputERPTableViewController.h"
#import "InputERPFunctionViewController.h"

#define ACTION_HANDLE @"HANDLE"
#define ACTION_TEMPLATE @"TEMPLATE"

@interface InputERPTableViewController ()
@property (nonatomic, strong) UIBarButtonItem *funcItem;
@end

@implementation InputERPTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - 获取功能菜单
-(void)requestFunctionMenu {
    NSString *templateGuid = self.viewModel.dataModel.templates.firstObject.dataDic[@"GUID"];
    //无GUID，视为新档案。无需请求功能菜单
    if (isEmptyString(templateGuid)) {
        [self navigaRightBarItemTypeByNoneFunctionMenu];
        return;
    }
    /*    获取按钮配置(syncButtonConfig)
     **   参数说明：TYPE 模板类型；GUID：模板的GUID
     **   返回值说明：DATA:[Obj1,obj2] 数组中每个成员生成一个按钮
     **   pfy 2018-07-23
     */
    NSMutableDictionary *postData = [[NSMutableDictionary alloc] init];
    postData[@"TYPE"] = [ToolHelper isEmptyStr:self.funcType];
    postData[@"GUID"] = [ToolHelper isEmptyStr:templateGuid];
    
    __weak typeof(self)weakSelf = self;
    [self Request:[self setupSaveInputDataUrl] queryType:@"syncButtonConfig" postData:postData success:^(id respone) {
        WebRequestData *data = (WebRequestData *)respone;
        if (!isEmptyString(data.Error) || isEmptyString(data.RequestData)) {
            [weakSelf navigaRightBarItemTypeByNoneFunctionMenu];
            return;
        }
        id dataObj = [ToolHelper JsonToDictionary:data.RequestData];
        if ([dataObj isKindOfClass:[NSDictionary class]]) {
            NSArray *array = ((NSDictionary *)dataObj)[@"DATA"];
            weakSelf.functionMenu = [[InputFunctionMenuClass alloc] initWithFunctionData:array];
            if (weakSelf.functionMenu.functionModels.count != 0) {
                [super requestFunctionMenu];
            } else {
                [weakSelf navigaRightBarItemTypeByNoneFunctionMenu];
            }
        }
    }];
}
//无功能按钮时，导航栏右侧按钮Type
-(void)navigaRightBarItemTypeByNoneFunctionMenu {
    if (self.navigaRightBarItemType == NavigationRightBarItemNormal || self.navigaRightBarItemType == NavigationRightBarItemFunction) {
        self.navigaRightBarItemType = NavigationRightBarItemNormal;
        
    } else if (self.navigaRightBarItemType == NavigationRightBarItemNone || self.navigaRightBarItemType == NavigationRightBarItemOnlyFunction) {
        self.navigaRightBarItemType = NavigationRightBarItemNone;
    }
    [super requestFunctionMenu];
}
-(void)creatEditBtn {
    if (self.navigaRightBarItemType == NavigationRightBarItemNormal) {
        [super creatEditBtn];
        
    } else if (self.navigaRightBarItemType == NavigationRightBarItemFunction) {
        UIBarButtonItem *btnItem = [[UIBarButtonItem alloc]
                                    initWithTitle:@"编辑" style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(editInput)];
        self.navigationItem.rightBarButtonItems = @[btnItem, self.funcItem];
        
    } else if (self.navigaRightBarItemType == NavigationRightBarItemOnlyFunction) {
        self.navigationItem.rightBarButtonItem = self.funcItem;
    }
}
-(void)creatInputDoneBtn {
    if (self.navigaRightBarItemType == NavigationRightBarItemNormal) {
        [super creatInputDoneBtn];
        
    } else if (self.navigaRightBarItemType == NavigationRightBarItemFunction) {
        UIBarButtonItem *btnItem = [[UIBarButtonItem alloc]
                                    initWithTitle:@"完成" style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(updateInputNodesByServer)];
        self.navigationItem.rightBarButtonItems = @[btnItem, self.funcItem];

    } else if (self.navigaRightBarItemType == NavigationRightBarItemOnlyFunction) {
        self.navigationItem.rightBarButtonItem = self.funcItem;
    }
}
#pragma mark - 弹出功能按钮
-(void)showFunctionMenu:(UIBarButtonItem *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"功能菜单" message:@"请选择您要进行的功能" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self popoverPresentationController];
    }];
    [alert addAction:cancel];
    for (InputFunctionModel *model in self.functionMenu.functionModels) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:model.name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self checkFunctionAuth:model pass:^{
                [self handleFunctionAction:model];
            }];
        }];
        [alert addAction:action];
    }
    if (alert.popoverPresentationController != nil) {
        UIView *view = [sender valueForKey:@"view"];
        alert.popoverPresentationController.sourceView = view;
        alert.popoverPresentationController.sourceRect = view.bounds;
    }
    [self presentViewController:alert animated:YES completion:nil];
}

//判断是否检测权限
-(void)checkFunctionAuth:(InputFunctionModel *)model pass:(void(^)())pass {
    if (!model.checkAuth) {
        pass();
    }
    /*    请求要执行的方法 model.checkAuthfunc
     **   参数说明：model.params
     **   返回值说明："1"有权限执行
     **   pfy 2018-07-24
     */
    [self showHudView:@"正在检测权限"];
    NSMutableDictionary *postData = [[NSMutableDictionary alloc] init];
    for (NSString *dataStr in model.params) {
        postData[dataStr] = [model selectParamesValue:dataStr];
    }
    __weak typeof(self)weakSelf = self;
    [self Request:[self setupSaveInputDataUrl] queryType:model.checkAuthfunc postData:postData success:^(id respone) {
        [weakSelf hiddenHudView];
        WebRequestData *data = (WebRequestData *)respone;
        if (!isEmptyString(data.Error) || isEmptyString(data.RequestData)) {
            NSString *errorStr = [NSString stringWithFormat:@"检测权限失败，原因：%@", isEmptyString(data.Error)? @"请求数据为空": data.Error];
            [self showHint:errorStr yOffset:HINTOFF];
            return;
        }
        id responeObj = [ToolHelper JsonToDictionary:data.RequestData];
        if ([responeObj isKindOfClass:[NSDictionary class]]) {
            NSString *resultData = ((NSDictionary *) responeObj)[@"DATA"];
            if ([resultData boolValue]) {
                pass();
            } else {
                [weakSelf showHint:@"检测权限失败，原因：无权限操作" yOffset:HINTOFF];
            }
        } else {
            [weakSelf showHint:@"检测权限失败，原因：数据格式错误" yOffset:HINTOFF];
        }
    }];
}
//具体的操作方法
-(void)handleFunctionAction:(InputFunctionModel *)model {
    if ([model.action isEqualToString:ACTION_TEMPLATE]) {
        InputERPFunctionViewController *functionVc = [[InputERPFunctionViewController alloc] init];
        functionVc.title = model.name;
        functionVc.requestUrl = [self setupSaveInputDataUrl];
        functionVc.requestFunc = model.func;
        functionVc.parames = model.params;
        [self.navigationController pushViewController:functionVc animated:YES];
        
    } else if ([model.action isEqualToString:ACTION_HANDLE]) {
        [self requestFunction:model];
    }
}
//请求操作方法
-(void) requestFunction:(InputFunctionModel *)model {
    /*    请求要执行的方法 model.func
     **   参数说明：model.params
     **   返回值说明：未定
     **   pfy 2018-07-24
     */
    NSMutableDictionary *postData = [[NSMutableDictionary alloc] init];
    for (NSString *dataStr in model.params) {
        postData[dataStr] = [model selectParamesValue:dataStr];
    }
    [self showHudView:@"正在执行"];
    __weak typeof(self)weakSelf = self;
    [self Request:[self setupSaveInputDataUrl] queryType:model.func postData:postData success:^(id respone) {
        [weakSelf hiddenHudView];
        WebRequestData *data = (WebRequestData *)respone;
        if (!isEmptyString(data.Error) || isEmptyString(data.RequestData)) {
            NSString *errorStr = [NSString stringWithFormat:@"操作失败，原因：%@", isEmptyString(data.Error)? @"请求数据为空": data.Error];
            [self showHint:errorStr yOffset:HINTOFF];
            return;
        }
        id responeObj = [ToolHelper JsonToDictionary:data.RequestData];
        if ([responeObj isKindOfClass:[NSDictionary class]]) {
            NSString *resultData = ((NSDictionary *) responeObj)[@"DATA"];
            if ([resultData boolValue]) {
                NSString *resultMsg = [ToolHelper isEmptyStr:((NSDictionary *) responeObj)[@"MSG"]];
                [weakSelf showHintOnWindow:[NSString stringWithFormat:@"操作成功,%@。", resultMsg] yOffset:HINTOFF];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [weakSelf showHint:@"操作失败，原因：无权限操作" yOffset:HINTOFF];
            }
        }
    }];
}
-(UIBarButtonItem *)funcItem {
    if (!_funcItem) {
        _funcItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:GetBundleImage(@"RomensUISDK.bundle/InputView",@"ic_select_more")] style:UIBarButtonItemStylePlain target:self action:@selector(showFunctionMenu:)];
    }
    return _funcItem;
}
-(void)checkEditAuth {
    [super editInput];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
